//
//  WHYNewsDetailViewController.m
//  News163
//
//  Created by 王洪运 on 16/1/3.
//  Copyright © 2016年 王洪运. All rights reserved.
//

#import "WHYNewsDetailViewController.h"
#import "Masonry.h"
#import "WHYHeadLine.h"
#import "WHYNewsDetailImage.h"
#import "WHYNewsDetail.h"
#import "WHYHTTPManager.h"
#import "SVProgressHUD.h"


@interface WHYNewsDetailViewController ()<UIWebViewDelegate>

@property (strong, nonatomic) UIWebView *webView;

@property (strong, nonatomic) WHYNewsDetail *newsDetail;

@end

@implementation WHYNewsDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"新闻详情";
    self.webView.delegate = self;
    
    [self setupUI];
    
    [self loadNewsDetail];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 加载新闻详情数据
-(void)loadNewsDetail {
    
    [SVProgressHUD show];
    
    [[WHYHTTPManager manager] loadNewsDetailRequestWithDocid:self.headLine.docid finishedHandler:^(id result, NSError *error) {
        
        [SVProgressHUD dismiss];
        
        if (error) {
            [SVProgressHUD showErrorWithStatus:@"网络请求出错,请重试"];
            NSLog(@"%@",error);
            return;
        }
        
        NSDictionary *dict = result[self.headLine.docid];
        
        self.newsDetail = [WHYNewsDetail newsDetailWithDict:dict];
        
        [self showNewsDetail];
    }];
    
}

#pragma mark - 显示新闻详情
-(void)showNewsDetail {
    
    NSMutableString *html = [NSMutableString string];
    
    [html appendString:@"<html>"];
    [html appendString:@"<head>"];
    [html appendString:[NSString stringWithFormat:@"<link rel=\"stylesheet\" href=\"%@\"",[[NSBundle mainBundle] URLForResource:@"WHYNewsDetaile.css" withExtension:nil]]];
    [html appendString:@"</head>"];
    [html appendString:@"<body>"];
    
    [html appendString:[self setupBody]];
    
    [html appendString:@"</body>"];
    [html appendString:@"</html>"];
    
    [self.webView loadHTMLString:html baseURL:nil];
    
}

-(NSString *)setupBody {
    
    NSMutableString *body = [NSMutableString string];
    
    [body appendFormat:@"<div class=\"title\">%@</div>",self.newsDetail.title];
    
    [body appendFormat:@"<div class=\"time\">%@</div>",self.newsDetail.ptime];
    
    [body appendString:self.newsDetail.body];
    
    for (WHYNewsDetailImage *newsDetailImg in self.newsDetail.img) {
        
        NSMutableString *imgHtml = [NSMutableString string];
        
        [imgHtml appendString:@"<div class=\"img-parent\">"];
        
        NSArray *pixel = [newsDetailImg.pixel componentsSeparatedByString:@"*"];
        
        int width = [pixel.firstObject intValue];
        int height = [pixel.lastObject intValue];
        
        int maxWidth = [UIScreen mainScreen].bounds.size.width * 0.6;
        
        if (width > maxWidth) {
            height = (int)(height * maxWidth / width);
            width = maxWidth;
        }
        
        NSString *onload = @"this.onclick = function() {"
                                                 "window.location.href = 'why:saveImageToAblum:&' + this.src"
                                                 "};";
        [imgHtml appendFormat:@"<img onload=\"%@\" width=\"%d\" height=\"%d\" src=\"%@\">",onload, width, height, newsDetailImg.src];
        [imgHtml appendString:@"</div>"];
        
        [body replaceOccurrencesOfString:newsDetailImg.ref withString:imgHtml options:kNilOptions range:NSMakeRange(0, body.length)];
        
    }
    
    return  body;
}

#pragma mark - UIWebViewDelegate
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSString *urlStr = request.URL.absoluteString;
    NSRange range = [urlStr rangeOfString:@"why:"];
    
    if (range.length == 0) {
        return YES;
    }
    
    NSUInteger loc = range.location + range.length;
    NSString *path = [urlStr substringFromIndex:loc];
    
    NSArray *methodAndParameterArr = [path componentsSeparatedByString:@"&"];
    
    NSString *methodName = methodAndParameterArr.firstObject;
    
    NSString *parameter = nil;
    if (methodAndParameterArr.count > 1) {
        parameter = methodAndParameterArr.lastObject;
    }
    
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    SEL selector = NSSelectorFromString(methodName);
    if ([self respondsToSelector:selector]) {
        [self performSelector:selector withObject:parameter];
    }
#pragma clang diagnostic pop
    
    return NO;
}

#pragma mark - 图片保存
-(void)saveImageToAblum:(NSString *)imageString {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"是否保存图片到相册" preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
//       从网页缓存中取得图片  -->  当网页加载完成时,网页上的图片已经被加载好,并缓存到NSURLCache中了
        NSURLCache *cache = [NSURLCache sharedURLCache];
        
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageString]];
        NSCachedURLResponse *cachedURLResponse = [cache cachedResponseForRequest:request];
        NSData *imageData = cachedURLResponse.data;
        UIImage *image = [[UIImage alloc] initWithData:imageData];
        
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:nil]];
     
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 保存图片成功时调用的方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"图片保存失败"];
    }else {
        [SVProgressHUD showSuccessWithStatus:@"图片保存成功"];
    }
    
}

#pragma mark - setupUI
-(void)setupUI {
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self.view addSubview:self.webView];
    
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).offset(64);
        make.left.right.bottom.mas_equalTo(self.view);
    }];
    
}

#pragma mark - 懒加载
-(UIWebView *)webView {
    if (_webView == nil) {
        _webView = [[UIWebView alloc] init];
    }
    return _webView;
}

@end
